import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;


public class Server{
	private static final int port = 7789;
	private Database db;
	private ServerSocket sock;
	private ThreadPool pool;
	private int threads;
	public static HashMap<Integer, Station> stations = new HashMap<Integer, Station>();
	
	
	public Server() {
		db = new Database("jdbc:mysql://localhost/unwdmi","root","");
		
		pool = new ThreadPool(810);
		
    	listen();
	}
	
    public void listen() {
    	try {
    		sock = new ServerSocket(port);
    		Socket clientSocket;
    		
//			StationCollector stationCollector = new StationCollector(db);
//			
//    		pool.add(stationCollector);
    		WriteThread writeThread1 = new WriteThread(db);
			pool.add(writeThread1);
			WriteThread writeThread2 = new WriteThread(db);
			pool.add(writeThread2);
			WriteThread writeThread3 = new WriteThread(db);
			pool.add(writeThread3);
			WriteThread writeThread4 = new WriteThread(db);
			pool.add(writeThread4);
    		
    		// Listen for connection
    		while(true) {	  
    			clientSocket = sock.accept();
    			WriteThread writeThread = writeThread1;
    			if(threads >= 200 && threads < 400) writeThread = writeThread2;
    			if(threads >= 400 && threads < 600) writeThread = writeThread3;
    			if(threads >= 600 && threads <= 800) writeThread = writeThread4;
    			ClientThread clientThread = new ClientThread(clientSocket,db,writeThread);       		
    			pool.add(clientThread);
    			threads++;
    		}
	    } catch (IOException e){
	    	System.err.println(e);
	    }
    }

}
